<template>
  <div class="app-container">
    <div style="width: 40%; margin: auto">
      <p v-text="emailTip"/>
      <p style="font-size: small; color: grey">
        如果长时间未收到验证码，请检查垃圾箱
      </p>
      <br>
      <el-form ref="mail" :model="value" label-width="120px" label-position="left">
        <el-form-item
          :label="emailLabel"
          :rules="[
            { required: true, validator: mailRule, trigger: 'blur' }
          ]"
          prop="email">
          <el-input v-model="value.email"/>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, validator: codeRule, trigger: 'blur' }
          ]"
          prop="code"
          label="填写验证码：">
          <el-input v-model="value.code">
            <el-button v-if="showBtn" slot="append" :disabled="disableBtn" type="text" plain @click="getEmailCode">获取验证码</el-button>
            <span v-else slot="append">{{ countTime }} s</span>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="saveBtn" type="primary" plain @click="saveChange">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>

import codeApi from '@/api/ucenter/code'
import userApi from '@/api/ucenter/user'

export default {
  name: 'Email',

  data() {
    return {
      value: {
        email: '',
        code: ''
      },
      disableBtn: false,
      showBtn: true,
      countTime: 60,
      saveBtn: false,
      sendMail: ''
    }
  },

  computed: {

    emailTip() {
      if (this.$route.params.email === '' || this.$route.params.email === undefined) {
        return ''
      } else {
        return '验证码将发送到' +
          this.$route.params.email.substr(0, 3) + ' * * * ' + this.$route.params.email.substr(this.$route.params.email.indexOf('@')) +
          '邮箱'
      }
    },

    emailLabel() {
      return this.$route.params.email === '' ? '待绑定邮箱：' : '待修改邮箱：'
    }

  },

  created() {
    if (this.$route.params.email === undefined) {
      this.$router.push({ path: '/ucenter/profile' })
    }
  },

  mounted() {
    window.onbeforeunload = function(e) {
      e = e || window.event
      console.log(e)
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示'
      }

      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '关闭提示'
    }
  },

  methods: {

    getEmailCode() {
      let email = this.value.email
      if (this.$route.params.email !== '' && this.$route.params.email !== undefined) {
        email = ''
      }
      this.disableBtn = true
      this.sendMail = email
      codeApi.sendMailCode(email).then(res => {
        this.disableBtn = false
        this.showBtn = false
        this.timer = setInterval(() => {
          this.countTime--
          if (this.countTime === 0) {
            this.countTime = 60
            this.showBtn = true
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message({
          type: 'success',
          message: res.result
        })
      }).catch(error => {
        this.disableBtn = false
        console.log(error)
      })
    },

    mailRule(rule, value, callback) {
      if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        callback(new Error('请输入合法的邮箱地址'))
      }
      if (this.sendMail !== '' && this.sendMail !== this.value.email) {
        callback(new Error('请绑定获取验证码的邮箱'))
      }
      callback()
    },

    codeRule(rule, value, callback) {
      if (!/^\d{6}$/.test(value)) {
        callback(new Error('请输入6位数字验证码'))
      }
      callback()
    },

    saveChange() {
      this.$refs.mail.validate(valid => {
        if (valid) {
          this.saveBtn = true
          const value = {
            key: this.value.email,
            code: this.value.code
          }
          userApi.updateEmail(value).then(res => {
            this.saveBtn = false
            this.$message({
              type: 'success',
              message: res.result
            })
            this.$router.push({ path: '/ucenter/profile' })
          }).catch(error => {
            this.saveBtn = false
            console.log(error)
          })
        }
      })
    }

  }
}
</script>
